package cn.iocoder.yudao.module.asasc.job;

import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.module.asasc.controller.admin.campaign.vo.AsaAppConfigPageReqVO;
import cn.iocoder.yudao.module.asasc.controller.admin.openapi.vo.CampaignUnionRespVO;
import cn.iocoder.yudao.module.asasc.dal.dataobject.campaign.AsaAppConfigDO;
import cn.iocoder.yudao.module.asasc.service.campaign.AsaAppConfigService;
import cn.iocoder.yudao.module.asasc.service.campaign.CampaignDataApiServiceImpl;
import cn.iocoder.yudao.module.asasc.service.campaign.CampaignDataService;
import cn.iocoder.yudao.module.asasc.service.campaign.CampaignGrandTotalsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ASA 广告系列日报表数据抓取 Job
 *
 * @since 2024-07-04
 */
@Component
@Slf4j
public class AsaCrawlerJob implements JobHandler {
    @Resource
    private CampaignDataApiServiceImpl campaignDataApiService;
    @Resource
    private CampaignDataService campaignDataService;
    @Resource
    private CampaignGrandTotalsService campaignGrandTotalsService;
    @Resource
    private AsaAppConfigService appConfigService;

    //    @TenantJob
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String execute(String param) throws Exception {
        //任务开始时间记录
        LocalDateTime startTime = LocalDateTime.now();
        String strDate;
        String endDate;
        if (param.contains("#")) {
            String[] params = param.split("#");
            strDate = params[0];
            endDate = params[1];
        } else {
            //获取昨天的日期
            strDate = LocalDateTime.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            endDate = strDate;
        }

        AsaAppConfigPageReqVO pageReqVO = new AsaAppConfigPageReqVO();
        pageReqVO.setJobEnable(CommonStatusEnum.ENABLE.getStatus());
        PageResult<AsaAppConfigDO> appConfigPage = appConfigService.getAsaAppConfigPage(pageReqVO);
        if (!appConfigPage.getList().isEmpty()) {
            List<AsaAppConfigDO> list = appConfigPage.getList();
            AtomicInteger totalCampaignsInserted = new AtomicInteger();
            AtomicInteger totalGrandTotalsInserted = new AtomicInteger();

            list.forEach(config -> {
                CampaignUnionRespVO campaigns = campaignDataApiService.getDailyCampaigns(config, strDate, endDate);

                campaigns.getCampaigns().stream()
                        .filter(Objects::nonNull)
                        .filter(a -> !Objects.isNull(a.getImpressions()))
                        .forEach(a -> {
                            campaignDataService.createCampaignData(a);
                            totalCampaignsInserted.getAndIncrement();
                        });

                campaigns.getGrandTotalsMap().forEach((k, v) -> {
                    campaignGrandTotalsService.createCampaignGrandTotals(v);
                    totalGrandTotalsInserted.getAndIncrement();
                });

                log.info("[execute][{}新增广告系列数据 ({}) 条]", config.getAdamId(), campaigns.getCampaigns().size());
                log.info("[execute][{}新增广告系列汇总数据 ({}) 条]", config.getAdamId(), campaigns.getGrandTotalsMap().size());

                try {
                    Thread.sleep(10 * 1000L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });

            // 任务结束时间记录
            LocalDateTime endTime = LocalDateTime.now();
            log.info("[execute][任务耗时 {} 毫秒]", Duration.between(startTime, endTime).toMillis());

            return String.format("新增广告系列数据 %s 条，汇总数据 %s 条。", totalCampaignsInserted, totalGrandTotalsInserted);
        }
        return "入参不对，[account#2024-07-05#2024-07-05]";
    }
}
